package com.bw.gmall.realtime.dws.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.common.base.BaseApp;
import com.bw.gmall.realtime.common.bean.TradeSkuOrderBean;
import com.bw.gmall.realtime.common.constant.Constant;
import com.bw.gmall.realtime.common.util.*;
import com.bw.gmall.realtime.dws.function.AsyncDimFunction;
import io.lettuce.core.RedisFuture;
import io.lettuce.core.api.StatefulRedisConnection;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.async.ResultFuture;
import org.apache.flink.streaming.api.functions.async.RichAsyncFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.hadoop.hbase.client.AsyncConnection;
import org.apache.hadoop.hbase.client.Connection;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.Duration;
import java.util.Collections;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * @projectName: gmalll2206
 * @package: com.bw.gmall.realtime.dws.app
 * @className: DwsTradeSkuOrderAsyncCacheRealWindow
 * @author: DuanYu
 * @description: TODO
 * @date: 2025/3/6 9:29
 * @version: 1.0
 */

public class DwsTradeSkuOrderAsyncCacheRealWindow extends BaseApp {
    public static void main(String[] args) {
        new DwsTradeSkuOrderAsyncCacheRealWindow().start(Constant.TOPIC_DWD_TRADE_ORDER_DETAIL, Constant.TOPIC_DWD_TRADE_ORDER_DETAIL, 4, 10029);
    }

    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> dataStreamSource) {
        SingleOutputStreamOperator<JSONObject> etlStream = getEtlStream(dataStreamSource);
        SingleOutputStreamOperator<JSONObject> wmStream = getWmStream(etlStream);
        KeyedStream<JSONObject, String> keyedIdStream = getKeyedIdStream(wmStream);
        SingleOutputStreamOperator<TradeSkuOrderBean> processStream = getProcessStream(keyedIdStream);
        KeyedStream<TradeSkuOrderBean, String> keyedSkuIdStream = getKeyedSkuIdStream(processStream);
        SingleOutputStreamOperator<TradeSkuOrderBean> reduce = getReduce(keyedSkuIdStream);
        SingleOutputStreamOperator<TradeSkuOrderBean> getSku = getSku(reduce);
        SingleOutputStreamOperator<TradeSkuOrderBean> getSpu = getSpu(getSku);
        SingleOutputStreamOperator<TradeSkuOrderBean> getTm = getTm(getSpu);
        SingleOutputStreamOperator<TradeSkuOrderBean> getC3 = getC3(getTm);
        SingleOutputStreamOperator<TradeSkuOrderBean> gerC2 = getC2(getC3);
//        AsyncDataStream.unorderedWait(gerC2, new AsyncDimFunction<TradeSkuOrderBean>("dim_base_category1") {
//            @Override
//            public void getResult(TradeSkuOrderBean tradeSkuOrderBean, JSONObject jsonObject) {
//                tradeSkuOrderBean.setCategory1Name(jsonObject.getString("name"));
//            }
//
//            @Override
//            public String getDimId(TradeSkuOrderBean tradeSkuOrderBean) {
//                return tradeSkuOrderBean.getCategory1Id();
//            }
//        },5000,TimeUnit.MINUTES,100).print();
        SingleOutputStreamOperator<TradeSkuOrderBean> getC1 = getC1(gerC2);
//        getC1.print();
//        getC1.map(new DorisMapFunction<>()).print();
        getC1.map(new DorisMapFunction<>()).sinkTo(FlinkSinkUtil.getDorisSink(Constant.DWS_TRADE_SKU_ORDER_WINDOW));
    }

    private static SingleOutputStreamOperator<TradeSkuOrderBean> getC1(SingleOutputStreamOperator<TradeSkuOrderBean> gerC2) {
        return AsyncDataStream.unorderedWait(gerC2, new RichAsyncFunction<TradeSkuOrderBean, TradeSkuOrderBean>() {
            private AsyncConnection hBaseAsyncConnection;
            private StatefulRedisConnection<String, String> redisAsyncConnection;

            @Override
            public void open(Configuration parameters) throws Exception {
                hBaseAsyncConnection = HbaseUtil.getHBaseAsyncConnection();
                redisAsyncConnection = RedisUtil.getRedisAsyncConnection();
            }

            @Override
            public void close() throws Exception {
                HbaseUtil.closeAsyncConnection(hBaseAsyncConnection);
                RedisUtil.closeRedisAsyncConnection(redisAsyncConnection);
            }

            @Override
            public void asyncInvoke(TradeSkuOrderBean tradeSkuOrderBean, ResultFuture<TradeSkuOrderBean> resultFuture) throws Exception {
                String category1Id = tradeSkuOrderBean.getCategory1Id();
                String redisKey = RedisUtil.getRedisKey("dim_base_category1", category1Id);
                CompletableFuture.supplyAsync(new Supplier<JSONObject>() {
                    @Override
                    public JSONObject get() {
                        String result = null;
                        RedisFuture<String> stringRedisFuture = redisAsyncConnection.async().get(redisKey);
                        try {
                            result = stringRedisFuture.get();
                        } catch (InterruptedException | ExecutionException e) {
                            resultFuture.completeExceptionally(e);
                            return null;
                        }
                        return JSON.parseObject(result);
                    }
                }).thenApplyAsync(new Function<JSONObject, JSONObject>() {
                    private JSONObject dimBaseCategory1;

                    @Override
                    public JSONObject apply(JSONObject jsonObject) {
                        if (jsonObject == null) {
                            try {
                                dimBaseCategory1 = HbaseUtil.getAsyncCells(hBaseAsyncConnection, Constant.HBASE_NAMESPACE, "dim_base_category1", category1Id);
                                redisAsyncConnection.async().setex(redisKey, 24 * 60 * 60, JSON.toJSONString(dimBaseCategory1));
                            } catch (IOException e) {
                                resultFuture.completeExceptionally(e);
                                return null;
                            }
                        } else {
                            dimBaseCategory1 = jsonObject;
                        }
                        return dimBaseCategory1;
                    }
                }).thenAccept(new Consumer<JSONObject>() {
                    @Override
                    public void accept(JSONObject jsonObject) {
                        if (jsonObject != null) {
                            tradeSkuOrderBean.setCategory1Name(jsonObject.getString("name"));
                        }
                        resultFuture.complete(Collections.singleton(tradeSkuOrderBean));
                    }
                }).exceptionally(ex -> {
                    resultFuture.completeExceptionally(ex);
                    return null;
                });
            }
        }, 5000, TimeUnit.MINUTES, 100);
    }


    private static SingleOutputStreamOperator<TradeSkuOrderBean> getC2(SingleOutputStreamOperator<TradeSkuOrderBean> getC3) {
        return AsyncDataStream.unorderedWait(getC3, new RichAsyncFunction<TradeSkuOrderBean, TradeSkuOrderBean>() {
            private AsyncConnection hBaseAsyncConnection;
            private StatefulRedisConnection<String, String> redisAsyncConnection;

            @Override
            public void open(Configuration parameters) throws Exception {
                hBaseAsyncConnection = HbaseUtil.getHBaseAsyncConnection();
                redisAsyncConnection = RedisUtil.getRedisAsyncConnection();
            }

            @Override
            public void close() throws Exception {
                HbaseUtil.closeAsyncConnection(hBaseAsyncConnection);
                RedisUtil.closeRedisAsyncConnection(redisAsyncConnection);
            }

            @Override
            public void asyncInvoke(TradeSkuOrderBean tradeSkuOrderBean, ResultFuture<TradeSkuOrderBean> resultFuture) throws Exception {
                String category2Id = tradeSkuOrderBean.getCategory2Id();
                String redisKey = RedisUtil.getRedisKey("dim_base_category2", category2Id);
                CompletableFuture.supplyAsync(new Supplier<JSONObject>() {
                    @Override
                    public JSONObject get() {
                        String result = null;
                        RedisFuture<String> stringRedisFuture = redisAsyncConnection.async().get(redisKey);
                        try {
                            result = stringRedisFuture.get();
                        } catch (InterruptedException | ExecutionException e) {
                            resultFuture.completeExceptionally(e);
                            return null;
                        }
                        return JSON.parseObject(result);
                    }
                }).thenApplyAsync(new Function<JSONObject, JSONObject>() {
                    private JSONObject dimBaseCategory2;

                    @Override
                    public JSONObject apply(JSONObject jsonObject) {
                        if (jsonObject == null) {
                            try {
                                dimBaseCategory2 = HbaseUtil.getAsyncCells(hBaseAsyncConnection, Constant.HBASE_NAMESPACE, "dim_base_category2", category2Id);
                                redisAsyncConnection.async().setex(redisKey, 24 * 60 * 60, JSON.toJSONString(dimBaseCategory2));
                            } catch (IOException e) {
                                resultFuture.completeExceptionally(e);
                                return null;
                            }
                        } else {
                            dimBaseCategory2 = jsonObject;
                        }
                        return dimBaseCategory2;
                    }
                }).thenAccept(new Consumer<JSONObject>() {
                    @Override
                    public void accept(JSONObject jsonObject) {
                        if (jsonObject != null) {
                            tradeSkuOrderBean.setCategory2Name(jsonObject.getString("name"));
                            tradeSkuOrderBean.setCategory1Id(jsonObject.getString("category1_id"));
                        }
                        resultFuture.complete(Collections.singleton(tradeSkuOrderBean));
                    }
                }).exceptionally(ex -> {
                    resultFuture.completeExceptionally(ex);
                    return null;
                });
            }
        }, 5000, TimeUnit.MINUTES, 100);
    }

    private static SingleOutputStreamOperator<TradeSkuOrderBean> getC3(SingleOutputStreamOperator<TradeSkuOrderBean> getTm) {
        return AsyncDataStream.unorderedWait(getTm, new RichAsyncFunction<TradeSkuOrderBean, TradeSkuOrderBean>() {
            private AsyncConnection hBaseAsyncConnection;
            private StatefulRedisConnection<String, String> redisAsyncConnection;

            @Override
            public void open(Configuration parameters) throws Exception {
                hBaseAsyncConnection = HbaseUtil.getHBaseAsyncConnection();
                redisAsyncConnection = RedisUtil.getRedisAsyncConnection();
            }

            @Override
            public void close() throws Exception {
                HbaseUtil.closeAsyncConnection(hBaseAsyncConnection);
                RedisUtil.closeRedisAsyncConnection(redisAsyncConnection);
            }

            @Override
            public void asyncInvoke(TradeSkuOrderBean tradeSkuOrderBean, ResultFuture<TradeSkuOrderBean> resultFuture) throws Exception {
                String category3Id = tradeSkuOrderBean.getCategory3Id();
                String redisKey = RedisUtil.getRedisKey("dim_base_category3", category3Id);
                CompletableFuture.supplyAsync(new Supplier<JSONObject>() {
                    @Override
                    public JSONObject get() {
                        String result = null;
                        RedisFuture<String> stringRedisFuture = redisAsyncConnection.async().get(redisKey);
                        try {
                            result = stringRedisFuture.get();
                        } catch (InterruptedException | ExecutionException e) {
                            resultFuture.completeExceptionally(e);
                            return null;
                        }
                        return JSON.parseObject(result);
                    }
                }).thenApplyAsync(new Function<JSONObject, JSONObject>() {
                    private JSONObject dimBaseCategory3;

                    @Override
                    public JSONObject apply(JSONObject jsonObject) {
                        if (jsonObject == null) {
                            try {
                                dimBaseCategory3 = HbaseUtil.getAsyncCells(hBaseAsyncConnection, Constant.HBASE_NAMESPACE, "dim_base_category3", category3Id);
                                redisAsyncConnection.async().setex(redisKey, 24 * 60 * 60, JSON.toJSONString(dimBaseCategory3));
                            } catch (IOException e) {
                                resultFuture.completeExceptionally(e);
                                return null;
                            }
                        } else {
                            dimBaseCategory3 = jsonObject;
                        }
                        return dimBaseCategory3;

                    }
                }).thenAccept(new Consumer<JSONObject>() {
                    @Override
                    public void accept(JSONObject jsonObject) {
                        if (jsonObject != null) {
                            tradeSkuOrderBean.setCategory2Id(jsonObject.getString("category2_id"));
                            tradeSkuOrderBean.setCategory3Name(jsonObject.getString("name"));
                        }
                        resultFuture.complete(Collections.singleton(tradeSkuOrderBean));
                    }
                }).exceptionally(ex -> {
                    resultFuture.completeExceptionally(ex);
                    return null;
                });
            }
        }, 5000, TimeUnit.MILLISECONDS, 100);
    }

    private static SingleOutputStreamOperator<TradeSkuOrderBean> getTm(SingleOutputStreamOperator<TradeSkuOrderBean> getSpu) {
        return AsyncDataStream.unorderedWait(getSpu, new RichAsyncFunction<TradeSkuOrderBean, TradeSkuOrderBean>() {
            private AsyncConnection hBaseAsyncConnection;
            private StatefulRedisConnection<String, String> redisAsyncConnection;

            @Override
            public void open(Configuration parameters) throws Exception {
                hBaseAsyncConnection = HbaseUtil.getHBaseAsyncConnection();
                redisAsyncConnection = RedisUtil.getRedisAsyncConnection();
            }

            @Override
            public void close() throws Exception {
                HbaseUtil.closeAsyncConnection(hBaseAsyncConnection);
                RedisUtil.closeRedisAsyncConnection(redisAsyncConnection);
            }

            @Override
            public void asyncInvoke(TradeSkuOrderBean tradeSkuOrderBean, ResultFuture<TradeSkuOrderBean> resultFuture) throws Exception {
                String trademarkId = tradeSkuOrderBean.getTrademarkId();
                String redisKey = RedisUtil.getRedisKey("dim_base_trademark", trademarkId);
                CompletableFuture.supplyAsync(new Supplier<JSONObject>() {
                    @Override
                    public JSONObject get() {
                        String result = null;
                        RedisFuture<String> stringRedisFuture = redisAsyncConnection.async().get(redisKey);
                        try {
                            result = stringRedisFuture.get();
                        } catch (InterruptedException | ExecutionException e) {
                            resultFuture.completeExceptionally(e);
                            return null;
                        }
                        return JSON.parseObject(result);
                    }
                }).thenApplyAsync(new Function<JSONObject, JSONObject>() {
                    private JSONObject baseTrademark;

                    @Override
                    public JSONObject apply(JSONObject jsonObject) {
                        if (jsonObject == null) {
                            try {
                                baseTrademark = HbaseUtil.getAsyncCells(hBaseAsyncConnection, Constant.HBASE_NAMESPACE, "dim_base_trademark", trademarkId);
                                redisAsyncConnection.async().setex(redisKey, 24 * 60 * 60, JSON.toJSONString(baseTrademark));
                            } catch (IOException e) {
                                resultFuture.completeExceptionally(e);
                                return null;
                            }
                        } else {
                            baseTrademark = jsonObject;
                        }
                        return baseTrademark;
                    }
                }).thenAccept(new Consumer<JSONObject>() {
                    @Override
                    public void accept(JSONObject jsonObject) {
                        if (jsonObject != null) {
                            tradeSkuOrderBean.setTrademarkName(jsonObject.getString("tm_name"));
                        }
                        resultFuture.complete(Collections.singleton(tradeSkuOrderBean));
                    }
                }).exceptionally(ex -> {
                    resultFuture.completeExceptionally(ex);
                    return null;
                });
            }
        }, 5000, TimeUnit.MILLISECONDS, 100);
    }

    private static SingleOutputStreamOperator<TradeSkuOrderBean> getSpu(SingleOutputStreamOperator<TradeSkuOrderBean> getSku) {
        SingleOutputStreamOperator<TradeSkuOrderBean> getSpu = AsyncDataStream.unorderedWait(getSku, new RichAsyncFunction<TradeSkuOrderBean, TradeSkuOrderBean>() {
            private AsyncConnection hBaseAsyncConnection;
            private StatefulRedisConnection<String, String> redisAsyncConnection;

            @Override
            public void open(Configuration parameters) throws Exception {
                hBaseAsyncConnection = HbaseUtil.getHBaseAsyncConnection();
                redisAsyncConnection = RedisUtil.getRedisAsyncConnection();
            }

            @Override
            public void close() throws Exception {
                HbaseUtil.closeAsyncConnection(hBaseAsyncConnection);
                RedisUtil.closeRedisAsyncConnection(redisAsyncConnection);
            }

            @Override
            public void asyncInvoke(TradeSkuOrderBean tradeSkuOrderBean, ResultFuture<TradeSkuOrderBean> resultFuture) throws Exception {
                String spuId = tradeSkuOrderBean.getSpuId();
                String redisKey = RedisUtil.getRedisKey("dim_spu_info", spuId);
                CompletableFuture.supplyAsync(new Supplier<JSONObject>() {
                    @Override
                    public JSONObject get() {
                        String result = null;
                        RedisFuture<String> stringRedisFuture = redisAsyncConnection.async().get(redisKey);
                        try {
                            result = stringRedisFuture.get();
                        } catch (InterruptedException | ExecutionException q) {
                            resultFuture.completeExceptionally(q);
                            return null;
                        }
                        return JSON.parseObject(result);
                    }
                }).thenApplyAsync(new Function<JSONObject, JSONObject>() {
                    @Override
                    public JSONObject apply(JSONObject jsonObject) {
                        JSONObject dimSpuInfo;
                        if (jsonObject == null) {
                            try {
                                dimSpuInfo = HbaseUtil.getAsyncCells(hBaseAsyncConnection, Constant.HBASE_NAMESPACE, "dim_spu_info", spuId);
                                redisAsyncConnection.async().setex(redisKey, 24 * 60 * 60, JSON.toJSONString(dimSpuInfo));
                            } catch (IOException e) {
                                resultFuture.completeExceptionally(e);
                                return null;
                            }
                        } else {
                            dimSpuInfo = jsonObject;
                        }
                        return dimSpuInfo;
                    }
                }).thenAccept(new Consumer<JSONObject>() {
                    @Override
                    public void accept(JSONObject jsonObject) {
                        if (jsonObject != null) {
                            tradeSkuOrderBean.setSpuName(jsonObject.getString("spu_name"));
                        }
                        resultFuture.complete(Collections.singleton(tradeSkuOrderBean));
                    }
                }).exceptionally(ex -> {
                    resultFuture.completeExceptionally(ex);
                    return null;
                });

            }
        }, 5000, TimeUnit.MILLISECONDS, 100);
        return getSpu;
    }

    private static SingleOutputStreamOperator<TradeSkuOrderBean> getSku(SingleOutputStreamOperator<TradeSkuOrderBean> reduce) {
        SingleOutputStreamOperator<TradeSkuOrderBean> tradeSkuOrderBeanSingleOutputStreamOperator = AsyncDataStream.unorderedWait(reduce, new RichAsyncFunction<TradeSkuOrderBean, TradeSkuOrderBean>() {
            private AsyncConnection hBaseAsyncConnection;
            private StatefulRedisConnection<String, String> redisAsyncConnection;

            @Override
            public void open(Configuration parameters) throws Exception {
                hBaseAsyncConnection = HbaseUtil.getHBaseAsyncConnection();
                redisAsyncConnection = RedisUtil.getRedisAsyncConnection();
            }

            @Override
            public void close() throws Exception {
                HbaseUtil.closeAsyncConnection(hBaseAsyncConnection);
                RedisUtil.closeRedisAsyncConnection(redisAsyncConnection);
            }

            @Override
            public void asyncInvoke(TradeSkuOrderBean tradeSkuOrderBean, ResultFuture<TradeSkuOrderBean> resultFuture) throws Exception {
                String skuId = tradeSkuOrderBean.getSkuId();
                String redisKey = RedisUtil.getRedisKey("dim_sku_info", skuId);
                CompletableFuture.supplyAsync(new Supplier<JSONObject>() {
                    @Override
                    public JSONObject get() {
                        String result = null;
                        RedisFuture<String> redisFuture = redisAsyncConnection.async().get(redisKey);
                        try {
                            result = redisFuture.get();
                        } catch (InterruptedException | ExecutionException e) {
                            resultFuture.completeExceptionally(e);
                            return null;
                        }
                        return JSONObject.parseObject(result);
                    }
                }).thenApplyAsync(new Function<JSONObject, JSONObject>() {
                    @Override
                    public JSONObject apply(JSONObject jsonObject) {
                        JSONObject dimSkuInfo = null;
                        if (jsonObject == null) {
                            try {
                                dimSkuInfo = HbaseUtil.getAsyncCells(hBaseAsyncConnection, Constant.HBASE_NAMESPACE, "dim_sku_info", skuId);
                                redisAsyncConnection.async().setex(redisKey, 24 * 60 * 60, JSON.toJSONString(dimSkuInfo));
                            } catch (IOException e) {
                                resultFuture.completeExceptionally(e);
                                return null;
                            }
                        } else {
                            dimSkuInfo = jsonObject;
                        }
                        return dimSkuInfo;
                    }
                }).thenAccept(new Consumer<JSONObject>() {
                    @Override
                    public void accept(JSONObject jsonObject) {
                        if (jsonObject != null) {
                            tradeSkuOrderBean.setSpuId(jsonObject.getString("spu_id"));
                            tradeSkuOrderBean.setTrademarkId(jsonObject.getString("tm_id"));
                            tradeSkuOrderBean.setCategory3Id(jsonObject.getString("category3_id"));
                        }
                        resultFuture.complete(java.util.Collections.singleton(tradeSkuOrderBean));
                    }
                }).exceptionally(ex -> {
                    resultFuture.completeExceptionally(ex);
                    return null;
                });
            }
        }, 5000, TimeUnit.MILLISECONDS, 100);
        return tradeSkuOrderBeanSingleOutputStreamOperator;
    }

    private static SingleOutputStreamOperator<TradeSkuOrderBean> getReduce(KeyedStream<TradeSkuOrderBean, String> keyedSkuIdStream) {
        return keyedSkuIdStream.window(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(5))).reduce(new ReduceFunction<TradeSkuOrderBean>() {
            @Override
            public TradeSkuOrderBean reduce(TradeSkuOrderBean value1, TradeSkuOrderBean value2) throws Exception {
                value1.setOriginalAmount(value1.getOriginalAmount().add(value2.getOriginalAmount()));
                value1.setCouponReduceAmount(value1.getCouponReduceAmount().add(value2.getCouponReduceAmount()));
                value1.setActivityReduceAmount(value1.getActivityReduceAmount().add(value2.getActivityReduceAmount()));
                value1.setOrderAmount(value1.getOrderAmount().add(value2.getOrderAmount()));
                return value1;
            }
        }, new ProcessWindowFunction<TradeSkuOrderBean, TradeSkuOrderBean, String, TimeWindow>() {
            @Override
            public void process(String s, ProcessWindowFunction<TradeSkuOrderBean, TradeSkuOrderBean, String, TimeWindow>.Context context, Iterable<TradeSkuOrderBean> iterable, Collector<TradeSkuOrderBean> collector) throws Exception {
                TimeWindow window = context.window();
                long start = window.getStart();
                long end = window.getEnd();
                for (TradeSkuOrderBean tradeSkuOrderBean : iterable) {
                    tradeSkuOrderBean.setStt(DateFormatUtil.tsToDateTime(start));
                    tradeSkuOrderBean.setEdt(DateFormatUtil.tsToDateTime(end));
                    tradeSkuOrderBean.setCurDate(DateFormatUtil.tsToDate(System.currentTimeMillis()));
                    collector.collect(tradeSkuOrderBean);
                }
            }
        });
    }

    private static KeyedStream<TradeSkuOrderBean, String> getKeyedSkuIdStream(SingleOutputStreamOperator<TradeSkuOrderBean> processStream) {
        return processStream.keyBy(new KeySelector<TradeSkuOrderBean, String>() {
            @Override
            public String getKey(TradeSkuOrderBean tradeSkuOrderBean) throws Exception {
                return tradeSkuOrderBean.getSkuId();
            }
        });
    }

    private static SingleOutputStreamOperator<TradeSkuOrderBean> getProcessStream(KeyedStream<JSONObject, String> keyedIdStream) {
        return keyedIdStream.process(new KeyedProcessFunction<String, JSONObject, TradeSkuOrderBean>() {
            private MapState<String, BigDecimal> mapStateDescriptor;

            @Override
            public void open(Configuration parameters) throws Exception {
                MapStateDescriptor<String, BigDecimal> orderStatus = new MapStateDescriptor<>("order_status", String.class, BigDecimal.class);
                orderStatus.enableTimeToLive(StateTtlConfig.newBuilder(Time.seconds(30)).build());
                mapStateDescriptor = getRuntimeContext().getMapState(orderStatus);
            }

            @Override
            public void processElement(JSONObject jsonObject, KeyedProcessFunction<String, JSONObject, TradeSkuOrderBean>.Context context, Collector<TradeSkuOrderBean> collector) throws Exception {
                BigDecimal split_original_amount = mapStateDescriptor.get("split_original_amount");
                BigDecimal split_activity_amount = mapStateDescriptor.get("split_activity_amount");
                BigDecimal split_coupon_amount = mapStateDescriptor.get("split_coupon_amount");
                BigDecimal split_total_amount = mapStateDescriptor.get("split_total_amount");

                split_original_amount = split_original_amount == null ? new BigDecimal(0) : split_original_amount;
                split_activity_amount = split_activity_amount == null ? new BigDecimal(0) : split_activity_amount;
                split_coupon_amount = split_coupon_amount == null ? new BigDecimal(0) : split_coupon_amount;
                split_total_amount = split_total_amount == null ? new BigDecimal(0) : split_total_amount;

                BigDecimal splitActivityAmount = jsonObject.getBigDecimal("split_activity_amount");
                BigDecimal splitCouponAmount = jsonObject.getBigDecimal("split_coupon_amount");
                BigDecimal splitTotalAmount = jsonObject.getBigDecimal("split_total_amount");

                BigDecimal sku_num = jsonObject.getBigDecimal("sku_num");
                BigDecimal order_price = jsonObject.getBigDecimal("order_price");
                BigDecimal originalAmount = sku_num.multiply(order_price);


                String skuId = jsonObject.getString("sku_id");
                String skuName = jsonObject.getString("sku_name");
                String id = jsonObject.getString("id");
                Long ts = jsonObject.getLong("ts");
                // 往下游发的数据
                collector.collect(TradeSkuOrderBean.builder()
                        .orderDetailId(id)
                        .skuName(skuName)
                        .ts(ts)
                        .skuId(skuId)
                        .originalAmount(originalAmount.subtract(split_original_amount))
                        .activityReduceAmount(splitActivityAmount.subtract(split_activity_amount))
                        .couponReduceAmount(splitCouponAmount.subtract(split_coupon_amount))
                        .orderAmount(splitTotalAmount.subtract(split_total_amount))
                        .build());

                mapStateDescriptor.put("split_original_amount", originalAmount);
                mapStateDescriptor.put("split_activity_amount", splitActivityAmount);
                mapStateDescriptor.put("split_coupon_amount", splitCouponAmount);
                mapStateDescriptor.put("split_total_amount", splitTotalAmount);
            }
        });
    }

    private static KeyedStream<JSONObject, String> getKeyedIdStream(SingleOutputStreamOperator<JSONObject> wmStream) {
        return wmStream.keyBy(new KeySelector<JSONObject, String>() {
            @Override
            public String getKey(JSONObject jsonObject) throws Exception {
                return jsonObject.getString("id");
            }
        });
    }

    private static SingleOutputStreamOperator<JSONObject> getWmStream(SingleOutputStreamOperator<JSONObject> etlStream) {
        return etlStream.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(5)).withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
            @Override
            public long extractTimestamp(JSONObject jsonObject, long l) {
                return jsonObject.getLong("ts") * 1000;
            }
        }));
    }

    private static SingleOutputStreamOperator<JSONObject> getEtlStream(DataStreamSource<String> dataStreamSource) {
        return dataStreamSource.flatMap(new RichFlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String s, Collector<JSONObject> collector) throws Exception {
                try {
                    if (s != null) {
                        JSONObject jsonObject = JSONObject.parseObject(s);
                        String sku_id = jsonObject.getString("sku_id");
                        String ts = jsonObject.getString("ts");
                        if (sku_id != null && ts != null) {
                            collector.collect(jsonObject);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}